package com.mapbased.wfw.bind;

import com.mapbased.wfw.*;

/**
 * <p>Title: </p>
 *
 * <p>Description:calculte relative url from web url(staart with "/") </p>
 *
 * <p>Copyright: Copyright (c) 2004</p>
 *
 * <p>Company: mapbased.com</p>
  General ,calculate a relative path is wastful , use /contextpath+/servletpath is better
 * @author chy_hs(Baily)
 * @version 1.0
 */
public class UrlBinding
    implements Binding
{
    String url;
    public UrlBinding(String url)
    {
        this.url=url;
    }

    /**
     * getValue
     *
     * @param context RenderContext
     * @return Object
     * @todo Implement this com.mapbased.wfw.Binding method
     */
    public Object getValue(RenderContext context)
    {
        return context.getRequest().getContextPath()+this.url;

//        String page=context.getRequest().getServletPath();
//
//        return calcaultUrl(this.url,page);

    }
    /**
     *
     *
     * @param urls String[]:the dest url splited by'/'
     * @param loadingPage String:the current page
     * @return String
     */
    public static String calcaultUrl(final String[] urls,String loadingPage)
    {

        String[] pages=loadingPage.trim().split("/");
        int ec=0;
        for(int i=0;i < pages.length - 1;i++)
        {
            if(urls.length > i && urls[i].equals(pages[i]))
            {
                ec++;
            }
            else
            {
                break;
            }
        }
        int pc=pages.length - ec - 1;
        StringBuffer  sartp=new StringBuffer(loadingPage.length());
        for(int i=0;i < pc;i++)
        {
            sartp.append( "../");
        }
        for(int i=ec;i < urls.length;i++)
        {
            sartp.append(urls[i]);
            if(i != urls.length - 1)
            {
                sartp.append("/");
            }
        }

        return sartp.toString();

    }

}
